package com.controller;

import com.domain.User;
import com.redis.RedisService;
import com.redis.UserKey;
import com.result.Result;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author lvcaihong
 * @dtae 2019/2/13 9:48
 */
@Controller
public class SampleController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisService redisService;


    @RequestMapping("/thymeleaf")
    public String thymeleaf(Model model){
        model.addAttribute("name","lvcaihong");
        return "hello";
    }


    @RequestMapping("/db")
    @ResponseBody
    public Result<User> dbGet(Model model){
       User user =  userService.getById(1);
       return Result.success(user);
    }

    @RequestMapping("/tx")
    @ResponseBody
    public Result<Boolean> dbTx(Model model){
        userService.tx();
        return Result.success(true);
    }

    /**
     * 关闭虚拟机防火墙，否则出现连接失败
     * @return
     */
    @RequestMapping("/redis/get")
    @ResponseBody
    public Result<User> redisGet(){
       /* String value = redisService.get("key",String.class);
        System.out.println(value);
        return Result.success(value);*/

       User user = redisService.get(UserKey.getById, ""+1,User.class);
        return Result.success(user);
    }


    @RequestMapping("/redis/set")
    @ResponseBody
    public Result<Boolean> redisSet(){
        //缺点：不同的人操作时，key可能相同，这样内容就会被覆盖，
        // 加一个前缀，key+prefix作为真正的key
        //v1
       /* redisService.set("name","lvcaihong");
        String value = redisService.get("name",String.class);
        return Result.success(value);*/

       //v2加前缀
        User user = new User();
        user.setName("11111");
        user.setId(1);
        redisService.set(UserKey.getById,""+1,user);
        return Result.success(true);
    }
}
